<template>
  <div class="pageBox">
    <!-- <div>{{ currentStep }}</div> -->
    <!-- <div>{{ currentForm }}</div> -->
    <!-- <div>{{stepLists}}</div> -->
    <a-row>
      <a-col
        span="8"
        style="background-color:#fff;height:85vh;border-radius:4px;padding:8px;overflow:auto;"
      >
        <div class="titleBox">
          <span>{{ mouldName }}</span>
        </div>
        <Tree
          ref="tree"
          v-model="currentStep"
          :treeData="stepLists"
          :defalutData="defalutData"
          @treeClick="isShowFormChange"
          @confirmRefreshData="refreshTree"
        ></Tree>
      </a-col>
      <a-col v-show="isStepEmpty" span="16" style="padding:8px 16px 8px 16px;">
        <a-button type="primary" @click="addStep('step')">+插入步骤</a-button>
      </a-col>
      <a-col
        v-if="isShowForm && Object.keys(currentStep).length"
        span="16"
        style="padding:8px 16px 8px 16px;"
      >
        <a-row>
          <a-col span="24">
            <div class="titleBox-child">
              
              <!-- <span v-show="!currentStep.isStep"></span> -->
              <span>{{ currentStep.name }}</span>
            </div>
            <div style="margin-top:16px;">
              <a-button type="primary" @click="() => (isDialogOpen = true)"
                >修改名称</a-button
              >

              <a-button
                v-show="currentStep.isStep"
                type="primary"
                @click="addStep('step')"
                >+插入步骤</a-button
              >
              <a-button
                v-show="currentStep.isStep && isAddFormLabel"
                type="primary"
                @click="addStep('formLabel')"
                >+插入表单项</a-button
              >
              <a-popconfirm
                style="float:right;"
                title="确认删除？"
                ok-text="是"
                cancel-text="否"
                @confirm="delStep"
              >
                <a-button type="danger">删除</a-button>
              </a-popconfirm>
            </div>
          </a-col>
          <a-col v-show="!currentStep.isStep" :span="24">
            <div v-if="formLoading" class="example">
              <a-spin class="load" />
            </div>
            <a-tabs default-active-key="1" @change="tabsHandle">
              <a-tab-pane
                v-for="item in formLists"
                :key="item.value"
                :tab="item.label"
              >
                <CreateForm v-model="currentForm[item.value]"></CreateForm>
              </a-tab-pane>
            </a-tabs>
            <a-row>
              <a-col :span="18">
                <div class="save-btn">
              <a-button type="primary" @click="confirmCurrentStep"
                >保存配置</a-button
              ><a-tooltip
                placement="top"
                class="info-icon"
                title="未保存的配置将会默认设置为输入框"
              >
                <a-icon type="info-circle" />
              </a-tooltip>
            </div>
              </a-col>
            </a-row>
            
          </a-col>
        </a-row>
      </a-col>
    </a-row>
    <UpdateNameDialog
      v-if="isDialogOpen"
      :openDialog.sync="isDialogOpen"
      :data="data"
      :title="currentStep.isStep ? '修改步骤名称' : '修改表单项名称'"
      @confirmRefreshData="getNameUpdate"
    ></UpdateNameDialog>
  </div>
</template>

<script>
import api from "@/server/mouldConfig.js";
import { getRoleId } from "@/unit/tool";
// import CheckStep from "@/components/checkStep/index";
import CreateForm from "@/components/createForm/index";
import Tree from "@/components/tree/index";
import UpdateNameDialog from "./components/updateNameDialog.vue";

function buildFormLists(obj) {
  // Object.keys(obj)
  return [
    {
      label: "装配",
      value: "f1"
    },
    {
      label: "自检",
      value: "f2"
    },
    {
      label: "专检",
      value: "f3"
    }
  ];
}
export default {
  name: "assembleTemplateNew",
  components: {
    // CheckStep,
    CreateForm,
    Tree,
    UpdateNameDialog
  },

  data() {
    return {
      userName: "",
      name: "",
      role: "",
      compId: "",
      mouldName: "",
      mouldId: "",
      formLoading: false,
      defalutData: {},
      isDialogOpen: false,
      data: {
        id: 0,
        name: ""
      },
      isShowForm: false,
      stepLists: [],
      currentStep: {},
      currentForm: {
        f1: [],
        f2: [],
        f3: []
      },
      formLists: []
    };
  },
  computed: {
    isAddFormLabel: function() {
      if (this.currentStep.children && this.currentStep.children.length > 0) {
        let isStep = this.currentStep.children.some(item => item.isStep);
        if (isStep) {
          return false;
        } else {
          return true;
        }
      }
      return true;
    },
    isStepEmpty: function() {
      if (this.stepLists && this.stepLists.length) {
        return false;
      }
      return true;
    }
  },
  watch: {
    currentStep: {
      deep: true,
      handler: function(newVal) {
        this.data.id = newVal.id || 0;
        this.data.name = newVal.name;
        let assembly = newVal.assembly || [];
        let selfCheck = newVal.selfCheck || [];
        let specialCheck = newVal.specialCheck || [];
        if (assembly.length) {
          assembly.forEach(item => {
            if (item.options && typeof item.options == "string") {
              item.options = eval("(" + item.options + ")");
            }
          });
        }
        if (selfCheck.length) {
          selfCheck.forEach(item => {
            if (item.options && typeof item.options == "string") {
              item.options = eval("(" + item.options + ")");
            }
          });
        }
        if (specialCheck.length) {
          specialCheck.forEach(item => {
            if (item.options && typeof item.options == "string") {
              item.options = eval("(" + item.options + ")");
            }
          });
        }

        this.currentForm = {
          f1: assembly || [],
          f2: selfCheck || [],
          f3: specialCheck || []
        };
      }
    }
  },
  methods: {
    getNameUpdate(name) {
      this.currentStep.name = name;
    },
    tabsHandle() {},
    //将有type和options对象的数组转化成含有type和optionsJson的对象
    objectToJson(object, key) {
      if (this.currentForm[key].length && this.currentForm[key][0].id) {
        let { id } = this.currentForm[key][0];
        object.id = id || "";
      }
      if (this.currentForm[key].length && this.currentForm[key][0].type) {
        object.type = this.currentForm[key][0].type;
        if (this.currentForm[key][0].options) {
          object.options = JSON.stringify(this.currentForm[key][0].options);
        }
      }
    },
    async confirmCurrentStep() {
      this.formLoading = true;
      let assembly = {};
      let selfCheck = {};
      let specialCheck = {};
      this.objectToJson(assembly, "f1");
      this.objectToJson(selfCheck, "f2");
      this.objectToJson(specialCheck, "f3");
      if (Object.keys(assembly).length) {
        assembly.checkType = 0;
      }
      if (Object.keys(selfCheck).length) {
        selfCheck.checkType = 1;
      }
      if (Object.keys(specialCheck).length) {
        specialCheck.checkType = 2;
      }
      let data = {
        id: this.currentStep.id,
        forms: [{ ...assembly }, { ...selfCheck }, { ...specialCheck }]
      };
      const res = await api.formUpdate(data);
      if (res.code != 200) {
        this.$message.error("提交配置失败");
        return;
      }
      let assList = res.data.filter(item => item.checkType == 0);
      let selfList = res.data.filter(item => item.checkType == 1);
      let specialList = res.data.filter(item => item.checkType == 2);
      this.currentStep.assembly = assList.length
        ? assList
        : this.currentStep.assembly;
      this.currentStep.selfCheck = selfList.length
        ? selfList
        : this.currentStep.selfCheck;
      this.currentStep.specialCheck = specialList.length
        ? specialList
        : this.currentStep.specialCheck;
      setTimeout(() => {
        this.formLoading = false;
        this.$message.success("提交配置成功");
      }, 500);

      this.refreshTree(this.currentStep);
    },

    // 获取查询模板步骤
    async findByMouldToProcess(params, key) {
      let _this = this;
      const res = await api.findByMouldToProcess({ mouldId: this.mouldId });

      if (res.code != 200) {
        this.$message.error("创建步骤失败");
        return;
      }
      let { data } = res;
      let stepLists = buildLists(data);
      this[key] = stepLists;
      if (stepLists.length) {
        if (params) {
          this.currentStep = params;
        } else {
          this.currentStep = stepLists[0];
          this.isShowForm = true;
        }
        this.defalutData = this.currentStep;
      }

      function buildLists(lists) {
        let _lists = [];
        _this.addKey(lists);
        _lists = lists;
        return _lists;
      }
    },
    addKey(list) {
      list.forEach(item => {
        item.scopedSlots = { icon: "icon-head", title: "custom" };
        if (item.children && item.children.length) {
          this.addKey(item.children);
        }
      });
    },
    addStep(key) {
      let isJumpQueue = false;
      if (
        key == "step" &&
        this.currentStep.children &&
        this.currentStep.children.length
      ) {
        let isStep = this.currentStep.children.some(item => item.isStep);
        if (!isStep) {
          isJumpQueue = true;
        }
      }
      this.$refs["tree"].addStep(key, isJumpQueue);
    },
    isShowFormChange() {
      this.isShowForm = true;
    },
    async delStep() {
      const res = await api.stepDel(this.currentStep.id);
      if (res.code == 9000) {
        this.$message.error(res.message);
        return;
      }
      if (res.code != 200) {
        this.$message.error("删除步骤失败");
        return;
      }
      let refreshData = {};
      if (res.data && Object.keys(res.data).length) {
        refreshData = res.data;
      }
      this.$message.success("删除成功");
      this.refreshTree(refreshData);
    },
    refreshTree(params) {
      this.findByMouldToProcess(params, "stepLists");
    }
  },
  mounted() {
    this.formLists = buildFormLists(this.currentForm);
    this.refreshTree();
  },
  created() {
    getRoleId(this);
    let { mouldName, mouldId } = this.$route.query;
    this.mouldName = mouldName;
    this.mouldId = mouldId;
  }
};
</script>

<style scoped="scoped" lang="less">
@import "./components/style.css";
.pageBox {
  padding: 16px;
  height: 100%;
  width: 100%;
}

.pageBox .titleBox {
  font-size: 20px;
  font-family: Microsoft YaHei;
  font-weight: 600;
  color: #1890ff;
  padding: 8px;
}
.pageBox .titleBox-child {
  font-size: 18px;
  font-family: Microsoft YaHei;
  font-weight: 600;
  padding: 0;
  color: #888b8d;
}
.example {
  z-index: 1000;
  text-align: center;
  line-height: 100%;
  background: rgba(0, 0, 0, 0.034);
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  .load {
    position: absolute;
    left: 50%;
    top: 50%;
  }
}
.save-btn {
  // width: 100%;
  // text-align: center;
  padding: 32px 0px;
  display:flex;
  align-items: flex-end;
  justify-content: center;
}
.info-icon {
  margin-left:4px;
  color:#1890ff;
  font-size:16px;
  
}
</style>
